from pydispatch import dispatcher
from gui import *
import usb
from signals import poll_usb


class USBDevices(object):
    class Device(object):
        def __init__(self, dev, bus): 
            (self.dev, self.bus) = dev, bus
            (self.mfr, self.des) = '', ''
            
        def __repr__(self): 
            return "%s-%s" % (self.dev, self.bus)

        def scan(self):
            cfgs = self.dev.configurations
            h = self.dev.open()
            try:
                self.mfr = h.getString(1, 30)
                self.des = h.getString(2, 30)
                #h.resetEndpoint()
            except usb.USBError, e:
                pass
            
    @property
    def connected(self):
        connected = []
        for bus in usb.busses():
            for dev in bus.devices:
                if dev.idProduct == 2: continue
                d = USBDevices.Device(dev=dev, bus=bus)
                d.scan()
                connected.append(d)
        return connected


class Graphic(object):
    COLOUR_SPLASH = Img('page1')
    FONT = Fnt('saved_by_zero', size=14, is_alias=True)


class Book(BookCommon):
    def __init__(self, *args, **kwargs):
        BookCommon.__init__(self, *args, **kwargs)
        self.usb = USBDevices()
        dispatcher.connect(self.poll_usb, signal=signals.poll_usb)
        self.usb_text = ''

    class Welcome(object):
        background = Graphic.COLOUR_SPLASH
        menus = [
            #Menu(tag='ipod', x1=285, y1=277, x2=357, y2=306,  img=Graphic.DESTINATION.ipod),
        ]

    PAGES = [
        Welcome,
    ]
    
    def get_fields(self, lines, x,y):
        for text in lines:
            field = Text(Graphic.FONT, 
                        text=text, 
                        colour=Colour.WHITE, 
                        x=x, y=y)
            yield field
            y += field.font.resource.get_height() + 2
                    
    def poll_usb(self):
        txt = []
        for dev in self.usb.connected:
            txt.append('%s-%s, id: %s' %(dev.mfr, dev.des, dev.dev.idProduct))
        self.usb_text = self.get_fields(lines = txt, x=215, y=160)

    def blit(self):
        mule = self.mule
        if self.page.background: 
            mule.surface.blit(self.page.background.surface, (0,0))

        for txt in self.usb_text: 
            txt.blit(mule.surface)
        
        for menu in self.page.menus: menu.blit(mule.surface)